package com.dlc.shop.live.api.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.dlc.shop.bean.dto.wukong.RegisterOrLoginDTO;
import com.dlc.shop.bean.enums.LiveRoomStatusType;
import com.dlc.shop.bean.model.User;
import com.dlc.shop.bean.vo.wukong.RegisterOrLoginVO;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.common.wukongim.constant.WuKongConstant;
import com.dlc.shop.live.common.constant.MsgType;
import com.dlc.shop.live.common.dto.LiveMessageDTO;
import com.dlc.shop.live.common.param.LiveMessageInfo;
import com.dlc.shop.live.common.service.LiveRoomProdService;
import com.dlc.shop.live.common.service.LiveRoomService;
import com.dlc.shop.live.common.vo.LiveMsgItem;
import com.dlc.shop.live.common.vo.LiveRoomProdVO;
import com.dlc.shop.live.common.vo.LiveRoomVO;
import com.dlc.shop.security.api.util.SecurityUtils;
import com.dlc.shop.security.common.util.AuthUserContext;
import com.dlc.shop.service.UserService;
import com.dlc.shop.wukongim.service.WuKongImService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author TRACK
 */
@RestController
@RequestMapping("/p/live/liveAnchor")
@Tag(name = "直播主播接口")
@AllArgsConstructor
public class LiveAnchorController {
    private static final Logger logger = LoggerFactory.getLogger(LiveAnchorController.class);

    private final LiveRoomService liveRoomService;
    private final LiveRoomProdService liveRoomProdService;
    private final WuKongImService wuKongImService;
    private final UserService userService;

    @PostMapping("/registerOrLogin")
    @Operation(summary = "主播注册或登录到im")
    @Parameter(name = "roomId", description = "直播间id", required = true)
    public ServerResponseEntity<RegisterOrLoginVO> registerOrLogin(@RequestBody LiveMessageDTO liveMessageDTO) {
        Long roomId = liveMessageDTO.getRoomId();
        List<String> list = StpUtil.getTokenValueListByLoginId(AuthUserContext.getUid());
        // 使用最开始登录的token
        String token = list.get(0);
        String userId = SecurityUtils.getUser().getUserId();
        LiveRoomVO livingRoom = liveRoomService.getLivingRoomInfo(userId, roomId);
        if (Objects.isNull(livingRoom)) {
            throw new YamiShopBindException("当前未有直播权限");
        }
        if (Objects.equals(livingRoom.getLiveStatus(), LiveRoomStatusType.FINISHED.value())) {
            throw new YamiShopBindException("当前直播已结束");
        }
        String liveAnchorUid = WuKongConstant.getLiveAnchorUid(userId, roomId);
        RegisterOrLoginDTO registerOrLoginDTO = new RegisterOrLoginDTO(liveAnchorUid, token, 0);
        // 注册
        wuKongImService.registerOrLogin(registerOrLoginDTO);
        // 添加订阅者
        String channelId = WuKongConstant.LIVE_CHANNEL_PREFIX + roomId;
        wuKongImService.addSubscriber(channelId, liveAnchorUid);
        RegisterOrLoginVO registerOrLoginVO = new RegisterOrLoginVO(liveAnchorUid, token);
        User user = userService.getUserByUserId(userId);
        registerOrLoginVO.setNickName(user.getNickName());
        return ServerResponseEntity.success(registerOrLoginVO);
    }

    @PostMapping("/updateExplainStatus")
    @Operation(summary = "更新商品讲解状态")
    public ServerResponseEntity<Void> updateExplainStatus(@RequestBody @Valid LiveMessageInfo liveMessageInfo) {
        Long roomId = liveMessageInfo.getRoomId();
        String channelId = WuKongConstant.LIVE_CHANNEL_PREFIX + roomId;
        if (Objects.equals(liveMessageInfo.getExplainStatus(), 0)) {
            // 商品取消讲解，发送消息
            sendNotExplainMsg(roomId, liveMessageInfo);
            return ServerResponseEntity.success();
        }
        // 检查商品状态
        List<LiveRoomProdVO> liveProdList = liveRoomProdService.listLiveRoomProd(roomId);
        Map<Long, LiveRoomProdVO> liveProdMap = liveProdList.stream().collect(Collectors.toMap(LiveRoomProdVO::getProdId, p -> p));
        LiveRoomProdVO liveRoomProdVO = liveProdMap.get(liveMessageInfo.getProdId());
        if (Objects.isNull(liveRoomProdVO)) {
            // 没有该商品，发送商品状态异常消息给所有人
            LiveMsgItem prodMsg = new LiveMsgItem(WuKongConstant.PROD_ERROR, "商品状态异常");
            wuKongImService.sendLiveRoomMessage(channelId, Json.toJsonString(prodMsg), null);
            return ServerResponseEntity.success();
        }
        int updateStatus = liveRoomProdService.updateExplainStatus(roomId, liveRoomProdVO.getProdId(), liveMessageInfo.getExplainStatus());
        if (updateStatus < 1) {
            // 没有更新，发送商品状态异常消息给所有人
            LiveMsgItem prodMsg = new LiveMsgItem(WuKongConstant.PROD_ERROR, "商品状态异常");
            wuKongImService.sendLiveRoomMessage(channelId, Json.toJsonString(prodMsg), null);
            return ServerResponseEntity.success();
        }
        // 发送商品讲解状态更新消息给所有人
        sendChangeExplainStatusMsg(channelId, liveMessageInfo, liveRoomProdVO);
        return ServerResponseEntity.success();
    }

    private void sendNotExplainMsg(Long roomId, LiveMessageInfo liveMessageInfo) {
        String channelId = WuKongConstant.LIVE_CHANNEL_PREFIX + roomId;
        liveRoomProdService.updateExplainStatus(roomId, liveMessageInfo.getProdId(), liveMessageInfo.getExplainStatus());
        LiveMsgItem liveMsgItem = new LiveMsgItem();
        liveMsgItem.setMsgType(MsgType.EXPLAIN_STATUS);
        liveMsgItem.setProdId(liveMessageInfo.getProdId());
        liveMsgItem.setExplainStatus(liveMessageInfo.getExplainStatus());
        liveMsgItem.setCmd(WuKongConstant.EXPLAIN_STATUS);
        // 发送商品讲解状态更新消息
        wuKongImService.sendLiveRoomMessage(channelId, Json.toJsonString(liveMsgItem), null);
    }

    private void sendChangeExplainStatusMsg(String channelId, LiveMessageInfo liveMessageInfo, LiveRoomProdVO liveRoomProdVO) {
        // 发送商品讲解状态更新消息给所有人
        LiveMsgItem liveMsgItemParam = new LiveMsgItem();
        liveMsgItemParam.setMsgType(MsgType.EXPLAIN_STATUS);
        liveMsgItemParam.setProdId(liveRoomProdVO.getProdId());
        liveMsgItemParam.setExplainStatus(liveMessageInfo.getExplainStatus());
        liveMsgItemParam.setCmd(WuKongConstant.EXPLAIN_STATUS);
        LiveMsgItem liveMsgItem = liveRoomProdService.handleLiveProd(liveMsgItemParam);
        if (Objects.isNull(liveMsgItem)) {
            // 商品异常，发送商品状态异常消息给所有人
            LiveMsgItem prodMsg = new LiveMsgItem(WuKongConstant.PROD_ERROR, "商品状态异常");
            wuKongImService.sendLiveRoomMessage(channelId, Json.toJsonString(prodMsg), null);
        }
        // 发送商品讲解状态更新消息
        wuKongImService.sendLiveRoomMessage(channelId, Json.toJsonString(liveMsgItem), null);
    }
}
